import { createModel } from '@rematch/core'
import type { RootModel } from '.'
import { IUserInfo, loginApi, loginReq } from '@/api/mock'
import { LocalCache } from '@/utils/cache'
import { getBrowserLang } from '@/utils/util'
import { LocalesEnum } from '@/types/global.d'
/**
 * 基本Model app.js, 在src/store/index.js中被挂载到store上，命名为app
 * 可用于存放通用信息，比如用户数据、角色、权限、省市区等通用数据
 * **/

type AppState = {
  locale: LocalesEnum
  token: string
  userinfo: IUserInfo | null
  state: number
}

export const app = createModel<RootModel>()({
  state: {
    locale: LocalCache.getItem('locale') ?? getBrowserLang() ?? LocalesEnum.zhCN,
    token: LocalCache.getItem('token') ?? '',
    userinfo: null, // 用户信息
    state: 0
  } as AppState,

  reducers: {
    setLocale(state, locale: LocalesEnum) {
      LocalCache.setItem('locale', locale)
      return { ...state, locale }
    },
    setToken(state, payload: string) {
      LocalCache.setItem('token', payload)
      return {
        ...state,
        token: payload
      }
    },
    setUserInfo(state, userinfo: IUserInfo) {
      return { ...state, userinfo }
    },
    increment: (state, payload = 1) => {
      return {
        ...state,
        state: state.state + payload
      }
    }
  },

  /** actions 可以是一个对象，也可以是一个函数，函数的第1个参数自动被注入dispatch(见models/test.js) **/
  effects: (dispatch) => ({
    getUserinfo(params: IUserInfo) {
      const user = { id: params.id, name: params.name || 'admin', avatar: '1231' }
      dispatch.app.setUserInfo(user) // 这个setUserInfo就是上面reducers中的setUserInfo
      return user
    },
    async login(data: loginReq) {
      const { data: res } = await loginApi(data)
      dispatch.app.setToken(res.token)
    }
  })
})
